package com.hangxingliu.flashalarm;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.os.Environment;

@SuppressLint("SimpleDateFormat")
public class VLog {
	
	private static boolean DEBUG = false;
	
	private static FileWriter logFile;
	private static BufferedWriter logWriter;
	
	private static SimpleDateFormat sdf = new SimpleDateFormat("MM_dd");
	private static SimpleDateFormat sdf_d = new SimpleDateFormat("MM_dd HH:mm:ss  ");
	
	public static boolean init() {
		if(!DEBUG)return false;
		if(logFile == null){
			Date now = new Date();
			
			File f= Environment.getExternalStorageDirectory();
			if(f == null)return false;
			if(!f.canWrite())return false;
			f = new File(f.getAbsolutePath()+"/FlashAlarm/log");
			if(!f.exists()){
				f.mkdirs();
			}
			if(!(f.exists() && f.canWrite()))return false;
			f = new File(f,"fa_log_"+sdf.format(now)+".log");
			try {
				logFile = new FileWriter(f, true);
				logWriter = new BufferedWriter(logFile);
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}
	
	public static boolean d(String message){
		if(!init())return false;
		return writeLog("Debug", message);
	}
	
	public static boolean e(String message){
		if(!init())return false;
		return writeLog("Error", message);
	}
	
	public static boolean w(String message){
		if(!init())return false;
		return writeLog("Warn", message);
	}
	
	public static String arrToString(Object[] objs,String arrName){
		String ret = "Array Output \""+arrName+"\"{\n";
		for(int i=0;i<objs.length;i++){
			ret+="  "+i+" : \""+objs[i].toString()+"\",\n";
		}
		ret+="}";
		return ret;
	}
	
	public static boolean close(){
		try {
			logWriter.close();
			logFile.close();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	private static boolean writeLog(String tag,String message){
		String wStr = sdf_d.format(new Date())+tag+"\n"+message+"\n";
		try {
			logWriter.write(wStr);
			logWriter.flush();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
}
